package ift605.EquationWithAgent.server.agent;

import java.io.IOException;

import udes.ds.agent.AbstractEquation;
import udes.ds.agent.Constant;
import ift605.EquationWithAgent.server.EquationMessage;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

public class ConstantEquationAgent extends DeriveSlaveAgent {
	private static final long serialVersionUID = 1L;

	protected void setup() {
		super.setup();
		addBehaviour(new DerivateBehaviour());
	}
	
	private class DerivateBehaviour extends CyclicBehaviour{
		private static final long serialVersionUID = 1L;

		@Override
		public void action() {
			ACLMessage request = null;
			MessageTemplate mt = MessageTemplate.MatchConversationId(EquationMessage.DERIVATE_ID);
			request = receive(mt);
			if(request == null){
				block();
			}
			else{
				try {
					// Doesn't matter what we receive, we return new Constant(0);
					EquationMessage equationRequest = (EquationMessage)request.getContentObject();
					ACLMessage response = new ACLMessage(ACLMessage.INFORM);
					response.addReceiver(request.getSender());
					AbstractEquation result = new Constant(0);
					response.setConversationId(EquationMessage.RESULT_ID);
					response.setContentObject(new EquationMessage(equationRequest.getRequestNumber(), result, equationRequest.getIdentifier()));
					send(response); 
				} 
				catch (IOException e) {
					e.printStackTrace();
				}
				catch (UnreadableException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public Class<?> GetDeriveClass() {
		return Constant.class;
	}
}
